;
(function(w) {

  new Vue({
    el: '#customerFollow',
    data: {
      listMenu: [
        {
          name: '未跟进过',
          code: 'FMWF',
          num: 0
        },
        {
          name: '跟进中',
          code: 'FMFI',
          num: 0
        },
        {
          name: '逾期未跟进',
          code: 'FMOWF',
          num: 0
        }
      ],
      selectedListMenuCode: [],
      keyWord: null,
      rpersonKeyword: null,
      columns: '',
      orders: '',
      rperson: {
        name: null,
        list: [],
        id: null
      }, // 对接人
      limit: ['10'],
      currentPage: 1,
      totalCount: 0,
      totalPage: 0,
      pageCounts: [{
        name: '10',
        code: '10'
      }, {
        name: '15',
        code: '15'
      }, {
        name: '20',
        code: '20'
      }],
      industryType: [],
      selectedIndustryType: [],
      customerStatuList: [
      ],
      selectedCustomerStatu: [],
      customerType: [{
        'name': '全部',
        'code': '#'
      }, {
        'name': '公司',
        'code': 'QY'
      }, {
        'name': '个人',
        'code': 'PE'
      }],
      selectedCustomerType: [],
      channelType: [], //渠道分类
      selectedChannelType: [],
      channelName: [], //渠道名称
      selectedChannelName: [],
      sourceList: [], //商机来源
      selectedSource: [],
      blackData: [],
      selectedBlackType: [],
      listData: [],
      countInfoData: [],
      excelURI: 'javascript:;',
      isExtenseFlag: false,
      configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
      module: '#',
      headArr: [],
      sortTableTitle: [],
      isScroll: false,
      isShowTableLayer: false,
      dateTimeUpdate: [],
      isActiveCode: '#',
      leftWidth: 0,
      rightWidth: 0,
      leftTableArr: [],
      rightTableArr: [],
      tbTitleWidth: {},
      lefthover: 0,
      tophover: 0,
      texthover: false,
      textLong: '',
      beginDate:'',
      endDate:''
    },
    filters: {
      formatYYYYMMddHHmm(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
      },
      formatUndefined: function(item) {
        if (!item && item !== 0) return '--'
        var result = item.substr(0, 5)
        return result
      },
      formatUndefinedFB: function(item) {
        if (!item) return '--'
        if (typeof item == 'number') {
          if (!isNaN(item) && item.toString().length == 13) {
            return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
          };
        }
        return item
      },
    },
    methods: {
			ZS_CUSTOMER_STATUS() {
			    var self = this
			    hlhttp.get({
			        url: 'configure/dict',
			        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
			        success: data => {
								data.unshift({dictName: '全部', dictCode: '#'})
			            self.customerStatuList = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			        }
			    })
			},
      selectMenuList() {
        this.currentPage = 1
        this.searchData()
      },
      //显示hover
      hoverText(e, v) {
        var s = this.$refs.scrollLeft.scrollLeft;
        var l = e.srcElement.parentNode.offsetLeft - s;
        var t = e.srcElement.parentNode.offsetTop + 40

        this.lefthover = l + 'px';
        this.tophover = t + 'px';
        this.texthover = true;
        this.textLong = v;
      },
      mouseleaveOut() {
        this.lefthover = 0 + 'px';
        this.tophover = 0 + 'px';
        this.texthover = false;
        this.textLong = '';
      },
      resetTabbar() {
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.searchData()
      },
      openSearch() {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      searchData() {
        var self = this;
        var submitData = {
          'customer_state': self.selectedCustomerStatu.length ? self.selectedCustomerStatu[0] : '#',
          'customer_type': self.selectedCustomerType.length ? self.selectedCustomerType[0] : '#',
          'industry': self.selectedIndustryType.length ? self.selectedIndustryType[0] : '#',
          'keyword': self.keyWord || '#',
          'follow_user_id': self.rperson.id || '#',
          'channel_category_code': self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code': self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'black_state': self.selectedBlackType.length ? self.selectedBlackType[0] : '#',
          'status': self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
          'limit': self.limit[0],
          'page': self.currentPage,
          'columns': self.columns || '#',
          'orders': self.orders || '#',
          'followup_time_begin': self.beginDate?self.beginDate + ' 00:00:00' : '#',
          'followup_time_end': self.endDate?self.endDate + ' 23:59:59' : '#'
        }


        hlhttp.get({
          url: 'customer/ctm_followup_manager_search',
          data: submitData,
          success: function(data) {
            self.listData = data.customerFMs
            self.totalCount = data.totalCount
            self.totalPage = data.totalPage
            self.countInfoData = data.countInfo

            let orderIndex = 1;
            data.customerFMs.forEach(el => {
              if (el.followupRecords.length == 0) el.followupRecords.push({})
              el.followupRecords.forEach(_el => {
                _el['order'] = orderIndex
                orderIndex++;
              })
            })

            self.listMenu.forEach(el => {
              if (el.code == 'FMWF') el['num'] = data.countInfo.FMWF;
              if (el.code == 'FMFI') el['num'] = data.countInfo.FMFI;
              if (el.code == 'FMOWF') el['num'] = data.countInfo.FMOWF;
            })

          }
        })
      },
      //查询
      search() {
        this.currentPage = 1
        this.limit = ['10']
        this.searchData()
      },
      reset() {
        this.columns = '',
        this.orders = '',
        this.isActiveCode = ''
        this.keyWord = null;
        this.selectedIndustryType = []
        this.selectedChannelType = []
        this.selectedChannelName = []
        this.selectedCustomerStatu = []
        this.selectedCustomerType = []
        this.selectedBlackType = []
        this.rperson = {
          name: null,
          list: [],
          id: null
        };
        this.beginDate = ''
        this.endDate = ''
        this.search()

      },
      // 获取对接人人员列表
      getRpersonData() {
        var self = this;
        hlhttp.get({
          url: 'tenants/users/_search',
          data: {
            'keyword': self.rpersonKeyword || '#',
            'first_order': 'Y'
          },
          success: function(data) {
            self.rperson.list = data;
            // 自动匹配  当输入的名字跟下拉列表中名字匹配时  则存储ID
            data.forEach(el => {
              if (self.rpersonKeyword.match(el.name)) {
                self.rperson.id = el.id;
                self.rperson.name = self.rpersonKeyword;
              }
            })
          }
        })
      },
      // 设置对接人name，获取id
      setRperson(name, id) {
        this.rperson = {
          name: name,
          list: [],
          id: id
        }
        this.rpersonKeyword = name
      },
      hideRpersonList() {
        this.rperson.list = [];
      },
      selectCustomerStatu(arr) {
        this.selectedCustomerStatu = [arr[0].code]
      },
      selectCustomerType(arr) {
        this.selectedCustomerType = [arr[0].code]
      },
      // 获取产业
      getIndustryType() {
        hlhttp.get({
          url: 'configure/industry/dict',
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.industryType = hlArrayUtil.replaceData(data, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })
      },
      selectIndustryType(arr) {
        this.selectedIndustryType = [arr[0].code]
      },
      // 渠道分类
      getChannelType() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_CATE'
          },
          success: data => {

            this.channelType = hlArrayUtil.replaceData(data, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })

      },
      selectChannelType(arr) {
        this.selectedChannelType = [arr[0].code]
        this.getChannelName()
      },
      // 获取渠道名称
      getChannelName() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_NAME',
            parent_dict_code: this.selectedChannelType[0]
          },
          success: data => {
            this.channelName = hlArrayUtil.replaceData(data, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })

      },
      selectChannelName(arr) {
        this.selectedChannelName = [arr[0].code]
      },
      getBlack() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_BLAKLIST_TYPE'
          },
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.blackData = hlArrayUtil.replaceData(data, [{
              key: 'dictName',
              rKey: 'name'
            }, {
              key: 'dictCode',
              rKey: 'code'
            }]);
          }
        })
      },
      selectBlackType(arr) {
        this.selectedBlackType = [arr[0].code]
      },
      selectPerNum(arr) {
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.searchData()
      },
      exportExcel() {
        const self = this;

        const submitData = {
          'keyword': self.keyWord || '#',
          'industry': self.selectedIndustryType.length ? self.selectedIndustryType[0] : '#',
          'customer_state': self.selectedCustomerStatu.length ? self.selectedCustomerStatu[0] : '#',
          'customer_type': self.selectedCustomerType.length ? self.selectedCustomerType[0] : '#',
          'follow_user_id': self.rperson.id || '#',
          'channel_category_code': self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code': self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'black_state': self.selectedBlackType.length ? self.selectedBlackType[0] : '#',
          'status': self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
          'columns': self.columns || '#',
          'orders': self.orders || '#',
          'followup_time_begin': self.beginDate?self.beginDate + ' 00:00:00' : '#',
          'followup_time_end': self.endDate?self.endDate + ' 23:59:59' : '#'
        }

        this.excelURI = null;

        $.ajax({
          url: exclUrl + 'resource/ctm_followup_manager_export',
          headers: {
            'token': Cookies.get("token")
          },
          data: submitData,
          type: 'get',
          success: data => {
            window.open(data.excel_url)
            // $('<a id="download" href="' + data.excel_url  + '"></a>').appendTo('body').click()
          }
        })

      },

      //更新时间
      sortBySTTime(item) {
        if (this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.searchData()
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_KHGJ'
          },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },
      //获取自定义表头配置信息
      customizeHeaderDt() {
        hlhttp.get({
          url: 'configure/customize_column_header',
          data: { module: 'ZHSH_KHGJ' },
          success: (data) => {
            data.customConfigList.map(item => {
              item.seq = Number(item.seq)
              item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
                this.dateTimeUpdate.push(item.value)
              }
            })
            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
            }

            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.lrTable()
          }
        })
      },
      //左右表格table
      lrTable() {
        this.leftWidth = 0;
        this.rightWidth = 0;
        this.leftTableArr = [];
        this.rightTableArr = [];

        this.headArr.map(item => {
          if (this.configType == 'JD') {
            if (item.baseFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
          if (this.configType == 'WZ') {
            this.lrTableDistinguish(item)
          }
          if (this.configType == 'PZ') {
            if (item.customShowFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
        })
        this.tbTitleWidthCalculation()
      },
      //左右表格区分
      lrTableDistinguish(item) {
        switch (item.unionTablePart) {
          case '1':
            this.leftTableArr.push(item)
            break;
          case '2':
            this.rightTableArr.push(item)
            break;
          default:
            break;
        }
      },
      //宽度计算
      tbTitleWidthCalculation() {

        this.leftTableArr.map(item0 => {
          this.leftWidth += Number(item0.styleWidth)
        })
        this.rightTableArr.map(item0 => {
          this.rightWidth += Number(item0.styleWidth)
        })
        this.tbTitleWidth = {
          width: (this.leftWidth + this.rightWidth) + 'px'
        }
        if (this.leftWidth + this.rightWidth < 960) {
          this.leftWidth = '50%'
          this.rightWidth = '50%'
          this.tbTitleWidth = {
            width: '100%'
          }
        }

      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(type) {
        this.configType = type;
        this.changeTableType(type)
        this.updateConfigType()
      },
      //更新自定义表头配置状态
      updateConfigType() {
        hlhttp.put({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_KHGJ',
            config_type: this.configType
          },
          success: () => {
            this.configTypeDt()
          }
        })
      },
      //改变头部
      changeTableType(type) {
        if (type == 'JD' || type == 'WZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
        }
        if (type == 'PZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
        }
        this.tbTitleWidthCalculation()
      },
      //显示某个自定义标题
      selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
      //关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
      showhighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'N'
      },
      //鼠标经过显示scroll
      showScroll() {
        this.isScroll = true;
      },
      //鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
        this.sortTableTitle.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            flex: item.flex,
            style_width: item.styleWidth,
            order_flag: item.orderFlag,
            order_name: item.orderName
          })
        })
        hlhttp.put({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_KHGJ',
            custom_config: JSON.stringify(dataArr)
          },
          success: (data) => {
            hl.toast('操作成功')
            this.closeTableLayer()
            this.updateConfigType()
          }
        })
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            if (self.sortTableTitle[beginIndex].unionTablePart == self.sortTableTitle[endIndex].unionTablePart) {
              newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            } else {
              hl.toast('合并表格无法跨表头排序')
            }
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
    },
    mounted: function() {
      hlSelectUi()
      this.getChannelType()
      this.getIndustryType()
      this.search()

      this.getBlack()
      this.initSortable()
      this.configTypeDt()
			this.ZS_CUSTOMER_STATUS()
    }
  })

}(window))
